import numpy as np
from matplotlib import pyplot as plt
from scipy.stats import median_abs_deviation
from scipy.optimize import curve_fit
import time


def gen_walk(
    n: int, mu: float, flight: bool, dim, wait=None
) -> tuple[np.ndarray, np.ndarray]:
    """Generates the 2D Levy flight or walk.

    Args:
        n (int): number of steps
        mu (float): exponent of the step distribution
        flight (bool): if True, generates Levy flight, otherwise Levy walk
        dim (int): dimension of the sample


    Returns:
        np.ndarray: generated path in the shape of (n+1, 2, dim), the first row is (0*dim, 0*dim)
        np.ndarray: time of the flight/walk after each step
    """
    path = np.zeros((n + 1, 2, dim))
    time = np.zeros((n + 1, dim))
    x, y, current_time = np.zeros(dim), np.zeros(dim), np.zeros(dim)
    if wait is not None:
        path = np.zeros((2 * n + 1, 2, dim))
        time = np.zeros((2 * n + 1, dim))

    for i in range(n):
        angle = np.random.uniform(0, 2 * np.pi, dim)
        step = (1 - np.random.uniform(0, 1, dim)) ** (-1 / (mu - 1))  # icdf pareto
        if wait is not None:
            cakanje = (1 - np.random.uniform(0, 1, dim)) ** (-1 / (wait - 1))
            current_time += step
            x += step * np.cos(angle)
            y += step * np.sin(angle)
            path[2 * i + 1][0] = x
            path[2 * i + 1][1] = y
            time[2 * i + 1] = current_time
            current_time += cakanje
            time[2 * i + 2] = current_time
            path[2 * i + 2] = path[2 * i + 1]
            continue
        if flight:
            current_time += 1
        else:
            current_time += step
        x += step * np.cos(angle)
        y += step * np.sin(angle)
        path[i + 1][0] = x
        path[i + 1][1] = y
        time[i + 1] = current_time
    return path, time


def demonstracija_pareto(mu: int, a: float, b: float, n: int) -> None:
    podatki = (
        np.random.uniform(0, 1, n) * (b ** (1 - mu) - a ** (1 - mu)) + a ** (1 - mu)
    ) ** (1 / (1 - mu))
    np.savetxt(
        f"data_pareto{int(10*mu)}.dat",
        podatki,
        header="x",
        comments="",
    )


# na žalost latex ni preveč zadovoljen z risanjem 10000 točk, zato za to delo zasužnjimo python
# na srečo lahko tudi python dovolj okranclja grafe, da so videti približno spodobno
def plot_random_walk(walk: np.ndarray, mu: float) -> None:
    """Plots the 2D random walk.

    Args:
        walk (np.ndarray): path in the shape of (n+1, 2)
        mu (float): exponent of the step distribution
    """
    plt.rc("text", usetex=True)
    plt.rc("font", family="serif")
    plt.rc("legend", fancybox=False)
    plt.rc("legend", edgecolor="k")
    plt.rc("savefig", dpi=300)
    plt.rc("savefig", bbox="tight")
    plt.figure(figsize=(3, 3))
    plt.plot(walk[:, 0], walk[:, 1], color="k", linewidth=0.5)
    plt.gca().set_aspect("equal")
    plt.grid("major")
    plt.xlabel(r"$x$")
    plt.ylabel(r"$y$")
    plt.title(rf"$N={len(walk)-1}$, $\mu={mu:.2f}$")
    plt.savefig(
        f"levy{len(walk)-1}_{mu}_walk.pdf",
        bbox_inches="tight",
    )
    plt.show()


def calculate_d_and_t(
    n: int, mu: float, flight: bool, dim: int, wait=None
) -> tuple[np.ndarray, np.ndarray]:
    """Returns evenly spaced times and distances at that times.

    Args:
        n (int): number of steps
        l (float): exponent of the step distribution
        flight (bool): if True, generates Levy flight, otherwise Levy walk
        dim (int): dimension of the sample
        wait (float): if not None, generates Levy walk with waiting times.

    Returns:
        np.ndarray: distances at times with dimension (500, dim)
        np.ndarray: times wit dimension (500, dim)"""
    if wait is not None and flight:
        raise ValueError("Cannot have waiting times and flight at the same time")
    positions, times = gen_walk(n, mu, flight, dim, wait)
    if flight:  # easy part
        distances = np.hypot(positions[:, 0, :], positions[:, 1, :])[100:]
        casi = np.arange(100, n + 1)
    else:  # difficult part
        # kdorkoli bere to kodo, naj si vzame nekaj minut in občuduje,
        # kako se da razmesariti numpy arraye z uporabo matrik kot indeksov
        max_time = np.min(times[-1])
        # casi, pri katerih bo samplal lokacija
        casi = np.linspace(100, max_time, 500)
        # inicializiramo array, kamor bomo shranjevali indekse seznama 'times', ki so najbližje vrednostim iz seznama 'casi'
        indices = np.zeros((len(casi), dim), dtype=int)
        for i in range(dim):
            # po vsakem stolpcu (vsak stolpec je en sprehod)
            indices[:, i] = np.searchsorted(times[:, i], casi)
        # priprava za numpy magic
        support_indices = np.repeat(np.arange(dim)[:, np.newaxis], len(casi), axis=1).T
        # literal black magic, vredno razmisleka
        time_before = times[indices - 1, support_indices]
        time_after = times[indices, support_indices]
        pos_before = positions[indices - 1, :, support_indices]
        pos_after = positions[indices, :, support_indices]

        # izračun deleža časa med dvema korakoma
        time_fraction = (np.repeat(casi[:, np.newaxis], dim, axis=1) - time_before) / (
            time_after - time_before
        )
        time_fraction = np.repeat(time_fraction[:, :, np.newaxis], 2, axis=2)
        # izračun vmesne pozicije
        positions_at_time = (1 - time_fraction) * pos_before + time_fraction * pos_after
        distances = np.hypot(positions_at_time[:, :, 0], positions_at_time[:, :, 1])
    return distances, casi


def racun(
    n: int, mu: float, flight: bool, dim: int, wait=None, savefile=False
) -> float:
    """Calculates the Levy exponent gamma for different scenarios.

    Args:
        n (int): number of steps
        l (float): exponent of the step distribution
        flight (bool): if True, generates Levy flight, otherwise Levy walk
        dim (int): dimension of the sample
        wait (float): if not None, generates Levy walk with waiting times
        savefile (bool): if True, saves the data to a file

    Returns:
        float: gamma
    """
    distances, casi = calculate_d_and_t(n, mu, flight, dim, wait)

    mads = median_abs_deviation(distances, axis=1)
    x = np.log(casi)
    y = 2 * np.log(mads)

    def func(x, a, b):
        return a * x + b

    popt, pcov = curve_fit(func, x, y)
    a, b = popt
    return a


def racun_z_nedoločenostmi(
    n: int, mu: float, flight: bool, dim: int, wait=None, savefile=False
) -> tuple[float, float]:
    """Calculates the Levy exponent gamma for different scenarios and returns
        the uncertainty from the regression.

    Args:
        n (int): number of steps
        l (float): exponent of the step distribution
        flight (bool): if True, generates Levy flight, otherwise Levy walk
        dim (int): dimension of the sample
        wait (float): if not None, generates Levy walk with waiting times

    Returns:
        float: gamma
    """
    distances, casi = calculate_d_and_t(n, mu, flight, dim, wait)
    mads = 2 * np.log(median_abs_deviation(np.split(distances, 10, axis=1), axis=2))
    mad_mean = np.mean(mads, axis=0)
    mad_std = np.std(mads, axis=0, ddof=1)
    x = np.log(casi)
    y = mad_mean
    yerr = mad_std

    def func(x, a, b):
        return a * x + b

    popt, pcov = curve_fit(func, x, y, sigma=yerr, absolute_sigma=True)
    a, b = popt
    a_err, b_err = np.sqrt(np.diag(pcov))
    if savefile:
        np.savetxt(
            f"data_levy{n}_{int(10*mu)}.dat",
            np.c_[x, y, yerr],
            header="x\ty\t\tyerr",
            comments="",
        )
    return a, a_err


def special_analysis(switch: bool) -> None:
    """Posebej analizira podatke točno na faznih prehodih. Dela samo s sprehodi.

    Args:
        switch (bool): za True vzame mu=2, za False vzame mu=3
    """
    dim = 10000
    distances, casi = calculate_d_and_t(10000, 2 if switch else 3, False, dim)
    mads = median_abs_deviation(np.split(distances, 10, axis=1), axis=2) ** 2
    mad_mean = np.mean(mads, axis=0)
    mad_std = np.std(mads, axis=0, ddof=1)
    x = casi
    y = mad_mean
    yerr = mad_std

    def f(x, a, b):
        return b * x**a

    def g(x, a, b):
        return b * x**a * np.log(x)

    def h(x, a, b):
        return b * x**a / np.log(x)

    popt, pcov = curve_fit(f, x, y, sigma=yerr, absolute_sigma=True)
    a, b = popt
    a_err, b_err = np.sqrt(np.diag(pcov))
    if switch:
        ropt, rcov = curve_fit(h, x, y, sigma=yerr, absolute_sigma=True)
        ra, rb = ropt
    else:
        ropt, rcov = curve_fit(g, x, y, sigma=yerr, absolute_sigma=True)
        ra, rb = ropt

    def calculate_R(x, y, funct, popt):
        residuals = y - funct(x, *popt)
        ss_res = np.sum(residuals**2)
        ss_tot = np.sum((y - np.mean(y)) ** 2)
        return 1 - ss_res / ss_tot

    R_naive = calculate_R(x, y, f, popt)
    R_improved = calculate_R(x, y, h if switch else g, ropt)

    np.savetxt(
        f"data_special_{'2' if switch else '3'}.dat",
        np.c_[x, y, yerr],
        header="x\ty\t\tyerr",
        comments="",
    )

    # plt.errorbar(x, y, yerr=yerr, fmt=".", capsize=2, color="k")
    # plt.plot(x, f(x, *popt), color="k")
    # plt.plot(x, h(x, *ropt) if switch else g(x, *ropt), color="r")
    # plt.show()

    print(f"gamma={a:.3f}+-{a_err:.3f}, b={b:.3f}+-{b_err:.3f}")
    print(
        f"alternative: gamma: {ra:.3f}+-{np.sqrt(rcov[0,0]):.3f}, rb={rb:.3f}+-{np.sqrt(rcov[1,1]):.3f}"
    )
    print(f"R^2={R_naive:.5f}, R^2 alternative={R_improved:.5f}")


def sequence(flight: bool, repetitions: int, wait=None) -> None:
    """Calculates the Levy exponent gamma for different mu-s multiple
    times and calculates their averages and standard deviations.

    Args:
        flight (bool): levy flight or walk
        repetitions (int): number of repetitions for averaging
        wait (float, optional): waiting parameter nu. Defaults to None.
    """
    mus = np.arange(1.1, 4, 0.1)
    gammas = np.zeros((len(mus), repetitions))
    for i_idx, i in enumerate(mus):
        for j in range(repetitions):
            gammas[i_idx, j] = racun(10000, i, flight, 1000, wait=wait)
            print(f"mu={i}, repetition {j+1}/{repetitions}")

    if flight:
        gammas = gammas ** (-1)
    gamma_means = np.mean(gammas, axis=1)
    gamma_std = np.std(gammas, axis=1, ddof=1)
    np.savetxt(
        f"data_levy_{'flight' if flight else 'walk'}{int(10*wait) if wait else ''}.dat",
        np.c_[mus, gamma_means, gamma_std],
        header="mu\tgamma\tgamma_err",
        comments="",
    )


def plot_many() -> None:
    """Ker latex ne zmore plotati 10000 točk, jih narišemo v pythonu."""
    plot_random_walk(gen_walk(10000, 3, True, 1)[0], 3)
    plot_random_walk(gen_walk(10000, 2, True, 1)[0], 2)
    plot_random_walk(gen_walk(1000, 3, True, 1)[0], 3)
    plot_random_walk(gen_walk(100, 3, True, 1)[0], 3)
    plot_random_walk(gen_walk(10, 3, True, 1)[0], 3)
    plot_random_walk(gen_walk(1000, 2, True, 1)[0], 2)
    plot_random_walk(gen_walk(100, 2, True, 1)[0], 2)
    plot_random_walk(gen_walk(10, 2, True, 1)[0], 2)


if __name__ == "__main__":
    np.random.seed(int(time.time() * 1000) % 2**32)
    repetitions = 10
    plot_many()
    racun_z_nedoločenostmi(10000, 2.5, False, 10000, savefile=True)
    sequence(True, repetitions)
    sequence(False, repetitions)
    sequence(False, repetitions, wait=3)
    sequence(False, repetitions, wait=2)
    sequence(False, repetitions, wait=1.5)
    demonstracija_pareto(1.5, 1, 10, 10000)
    demonstracija_pareto(2.5, 1, 10, 10000)
    special_analysis(False)
    special_analysis(True)
